package fr.gdi.android.news;

import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.android.extras.ColorDialog;
import com.android.extras.ColorPickListener;
import com.android.extras.DialogSeekBarPreference;

import fr.gdi.android.news.utils.Constants;
import fr.gdi.android.news.utils.Constants.Configuration;
import fr.gdi.android.news.utils.Constants.Preferences;
import fr.gdi.android.news.utils.PreferenceUtils;

public class WidgetAppearanceActivity extends PreferenceActivity implements OnPreferenceClickListener
{
    private int appWidgetId;
    private boolean liveWidget, needReload;

    private final static int THUMB_SIZE_WARNING_DIALOG = 1002;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        addPreferencesFromResource(R.xml.widget_appearances);
        
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        if (extras != null)
        {
            appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            liveWidget = extras.getBoolean(Constants.Configuration.LIVE_WIDGET, false);
            needReload = !liveWidget;
        }
        
        setupPreferences();
    }
    
    private void setupPreferences()
    {
        Context context = this;
        
        EditTextPreference widgetTitleFormat = (EditTextPreference) findPreference(Preferences.TITLE_FORMAT);
        widgetTitleFormat.setKey(PreferenceUtils.getWidgetPreferenceKey(Preferences.TITLE_FORMAT, appWidgetId));
        widgetTitleFormat.setText(PreferenceUtils.getStringPreference(this, Preferences.TITLE_FORMAT, appWidgetId, Configuration.DEFAULT_TITLE_FORMAT));
        
        ListPreference headlineSizePref = (ListPreference) findPreference(Preferences.HEADLINE_SIZE);
        headlineSizePref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.HEADLINE_SIZE, appWidgetId));
        String headlineSize = PreferenceUtils.getStringPreference(this, Preferences.HEADLINE_SIZE, appWidgetId, SimpleNewsEntry.FontSize.Normal.toString());
        headlineSizePref.setValue(headlineSize);
        
        ListPreference footerSizePref = (ListPreference) findPreference(Preferences.FOOTER_SIZE);
        footerSizePref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.FOOTER_SIZE, appWidgetId));
        String footerSize = PreferenceUtils.getStringPreference(this, Preferences.FOOTER_SIZE, appWidgetId, SimpleNewsEntry.FontSize.Normal.toString());
        footerSizePref.setValue(footerSize);
        
        ListPreference summarySizePref = (ListPreference) findPreference(Preferences.SUMMARY_SIZE);
        summarySizePref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.SUMMARY_SIZE, appWidgetId));
        String summarySize = PreferenceUtils.getStringPreference(this, Preferences.SUMMARY_SIZE, appWidgetId, SimpleNewsEntry.FontSize.Normal.toString());
        summarySizePref.setValue(summarySize);
        
        
        ListPreference bgPref = (ListPreference) findPreference(Preferences.BACKGROUND);
        bgPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.BACKGROUND, appWidgetId));
        String bg = PreferenceUtils.getBackground(this, appWidgetId);
        bgPref.setValue(bg);
        
        bgPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Preferences.BACKGROUND, appWidgetId));
        bgPref.setValue(PreferenceUtils.getBackground(context, appWidgetId));
        
        if (liveWidget)
        {
            bgPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    needReload = true;
                    return true;
                }
            });
            
        }
        
        CheckBoxPreference cbPref = (CheckBoxPreference) findPreference(Preferences.CAPITALIZE_KEY);
        cbPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.CAPITALIZE_KEY, appWidgetId));
        cbPref.setChecked(PreferenceUtils.getBooleanPreference(this, Preferences.CAPITALIZE_KEY, appWidgetId));
        
        CheckBoxPreference regHeadlinePref = (CheckBoxPreference) findPreference(Preferences.REGULAR_HEADLINE);
        regHeadlinePref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.REGULAR_HEADLINE, appWidgetId));
        regHeadlinePref.setChecked(PreferenceUtils.getBooleanPreference(this, Preferences.REGULAR_HEADLINE, appWidgetId));
        
        CheckBoxPreference use12HourPref = (CheckBoxPreference) findPreference(Preferences.USE_12_HOUR);
        use12HourPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.USE_12_HOUR, appWidgetId));
        use12HourPref.setChecked(PreferenceUtils.getBooleanPreference(this, Preferences.USE_12_HOUR, appWidgetId));
        use12HourPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                needReload = true;
                return true;
            }
        });
        
        CheckBoxPreference footerPref = (CheckBoxPreference) findPreference(Preferences.HIDE_FOOTER);
        footerPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.HIDE_FOOTER, appWidgetId));
        footerPref.setChecked(PreferenceUtils.getBooleanPreference(this, Preferences.HIDE_FOOTER, appWidgetId));
        
        CheckBoxPreference showImagesPref = (CheckBoxPreference) findPreference(Preferences.SHOW_IMAGES);
        showImagesPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.SHOW_IMAGES, appWidgetId));
        showImagesPref.setChecked(PreferenceUtils.getBooleanPreference(this, Preferences.SHOW_IMAGES, appWidgetId));
        
        DialogSeekBarPreference thumbSizePref = (DialogSeekBarPreference) findPreference(Preferences.THUMB_SIZE);
        thumbSizePref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Preferences.THUMB_SIZE, appWidgetId));
        int ts = PreferenceUtils.getIntPreference(this, Preferences.THUMB_SIZE, 42, appWidgetId);
        thumbSizePref.setValue(ts);
        
        thumbSizePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference arg0, Object arg1)
            {
                if ( arg1 != null ) 
                {
                    Integer val = (Integer) arg1;
                    if ( val > 192 ) 
                    {
                        boolean hideWarning = PreferenceUtils.getBooleanPreference(WidgetAppearanceActivity.this, "THUMB_SIZE_WARNING");
                        if (!hideWarning)
                        {
                            showDialog(THUMB_SIZE_WARNING_DIALOG);
                        }
                    }
                }
                return true;
            }
        });
        
        
        CheckBoxPreference squareCornersPref = (CheckBoxPreference) findPreference(Configuration.SQUARE_CORNERS);
        squareCornersPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Constants.Configuration.SQUARE_CORNERS, appWidgetId));
        squareCornersPref.setChecked(PreferenceUtils.getBooleanPreference(this, Configuration.SQUARE_CORNERS, appWidgetId));
        
        setupAppearanceAction(Preferences.HEADLINE_COLOR);
        setupAppearanceAction(Preferences.SUMMARY_COLOR);
        setupAppearanceAction(Preferences.FOOTER_COLOR);
        setupAppearanceAction(Preferences.WIDGET_TITLE_COLOR);
        /*
        Preference bPref = findPreference("BACKGROUND_FILE");
        bPref.setKey(PreferenceUtils.getWidgetPreferenceKey(Preferences.BACKGROUND_FILE, appWidgetId));
        bPref.setDefaultValue(PreferenceUtils.getStringPreference(this, Preferences.BACKGROUND_FILE, appWidgetId));
        bPref.setOnPreferenceClickListener(this);
        */
        Preference pref = findPreference("FINISH");
        pref.setOnPreferenceClickListener(this);
    }
    
    private void setupAppearanceAction(String key)
    {
        Preference pref = findPreference(key);
        pref.setOnPreferenceClickListener(this);
        
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int c = PreferenceUtils.getIntPreference(this, key, Color.WHITE, appWidgetId);
        Editor editor = prefs.edit();
        editor.putInt(PreferenceUtils.getWidgetPreferenceKey(key, appWidgetId), c);
        editor.commit();
    }
    
    /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == requestSelectBackground) 
        {
            String path = data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH);

            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            Editor editor = prefs.edit();
            editor.putString(PreferenceUtils.getWidgetPreferenceKey(Preferences.BACKGROUND_FILE, appWidgetId), path);
            editor.commit();
        }
        else 
        {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    */
    
    private boolean doNotShowAgain;
    
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch(id) {
        case THUMB_SIZE_WARNING_DIALOG:
            final Context ctx = this;
            
            AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
            AlertDialog dlg = builder1.create();
            dlg.setTitle(getString(R.string.appearance));
            LayoutInflater inflater1 = getLayoutInflater();
            View view1 = inflater1.inflate(R.layout.appearance_warning, null);
            TextView tv1 = (TextView) view1.findViewById(R.id.appearance_warning_text);
            tv1.setText(R.string.thumb_warning_text);
            CheckBox box = (CheckBox) view1.findViewById(R.id.donot_whow_again_cb);
            box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    doNotShowAgain = isChecked;
                }
            });
            dlg.setView(view1);
            dlg.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.cancel();
                }
            });
            dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog)
                {
                    PreferenceUtils.setBooleanPreference(ctx, "THUMB_SIZE_WARNING", doNotShowAgain);
                }
            });
            return dlg;
        }
        return super.onCreateDialog(id);
    }
    
    @Override
    public boolean onPreferenceClick(Preference preference)
    {
        final String key = preference.getKey();
        
        if (key.equals(Preferences.HEADLINE_COLOR) || key.equals(Preferences.SUMMARY_COLOR) || key.equals(Preferences.FOOTER_COLOR)
                || key.equals(Preferences.WIDGET_TITLE_COLOR))
        {
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            int c = PreferenceUtils.getIntPreference(this, key, Color.WHITE, appWidgetId);
            ColorDialog dlg = new ColorDialog(this, false, preference, c, new ColorPickListener() {
                @Override
                public void onPick(Object tag, int color)
                {
                    Editor editor = prefs.edit();
                    editor.putInt(PreferenceUtils.getWidgetPreferenceKey(key, appWidgetId), color);
                    editor.commit();
                }
            }, R.drawable.wheel);
            dlg.show();
            return true;
        }
        /*
        if ( key.endsWith("BACKGROUND_FILE") )
        {
            Intent intent = new Intent(this, FilePickerActivity.class);

             String p = PreferenceUtils.getStringPreference(this, Preferences.BACKGROUND_FILE, appWidgetId);
             if ( !TextUtils.isEmpty(p) ) 
             {
                 File f = new File(p);
                 if ( f.getParentFile().exists() ) 
                 {
                     intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, f.getParentFile().getPath());
                 }
                 else
                 {
                     intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory().getPath());
                 }
             }
             else 
             {
                 intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory().getPath());
             }
             
             
             // Show hidden files
             //intent.putExtra(FilePickerActivity.EXTRA_SHOW_HIDDEN_FILES, true);
    
             // Only make .png files visible
             ArrayList<String> extensions = new ArrayList<String>();
             extensions.add(".png");
             extensions.add(".jpg");
             intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);
    
             // Start the activity
             startActivityForResult(intent, requestSelectBackground);
             
             return true;
        }
        */
        if (key.equals("FINISH"))
        {
            Intent resultValue = new Intent();
            resultValue.putExtra("NEED_RELOAD", needReload);
            setResult(RESULT_OK, resultValue);
            super.finish();
            return true;
        }
        
        return false;
    }
}
